package top.kaoshanji.p1ch03a;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 代码清单 p1ch03a-02：通过保存流的数据进行流复用的示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/5 19:00
 */
public class InputStreamExample02 {

    private InputStream input;
    private byte[] data = new byte[0];

    public InputStreamExample02(InputStream input) throws IOException {
        this.input = input;
        save();
    }

    private void save() throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = input.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }

        data = output.toByteArray();
    }

    public InputStream getInputStream() {
        return new ByteArrayInputStream(data);
    }

}
